<?php
/*
 * @Date: 2022-09-27 11:23:42
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-07-25 10:26:32
 */
namespace Ldy\Middleware;

use Ldy\Models\SysLogs;
use think\facade\Request;

class Logs{
    
    public function handle($request, \Closure $next)
    {

        if(!$request->rule()->getRoute()){
            
            return redirect("/404.html");
        }

        $route = get_controller_action($request->rule()->getRoute());

        $controller = $route['controller'];//'\Ldy\Controller\Account';
        $action = $route['action'];//$request->action;
        $method = $request->method();
        $path = $request->url();
        $ip = $request->ip();
        $admin = session('admin');
        $reqData = ['post'=>$request->post(),'header' => $request->header(), 'get'=>$request->get()];

        $noRecordLog = $request->header('QsNoRecordLog');

        $response = $next($request);
        //不记录日志
        if($noRecordLog) return $response;

        // 获取控制器鉴权信息
        $class = new \ReflectionClass($controller);
        $properties = $class->getDefaultProperties();
       
        $classMethod = $class->getMethod($action);

        $doc = $classMethod->getDocComment();

        preg_match('/\{(.*)\}/', $doc, $match);
        $jsonStr = $match ? $match[0]:[];
        $json = empty($jsonStr) ? []:json_decode($jsonStr, true);

        $logs = $json ?? [];

        $status = $response->getCode();
        $res = $response->getData();

        if($properties['isRecordLogs'] && !empty($logs) && $status == 200 && !empty($res)){

            $code = $res['code'];
            if(isset($res['msg'])) $reqData['response'] = $res['msg'];

            if(empty($admin)) $admin = session('admin');
            $data = [];

            $logTitle = $action;
            if(isset($logs[$method])) $logTitle = is_array($logs[$method]) ?  $logs[$method]['title']:$logs[$method];
            
            $info = isset($res['data']) && !empty($res['data']) && is_array($res['data']) ? array_merge($res['data'],$reqData['post']):$reqData['post'];
            
            if($properties['title']) $logTitle = preg_replace('/{title}/', $properties['title'], $logTitle);

            $logTitle = preg_replace_callback('/\{(.*?)\}/', function($match) use ($info){
                if(count($match)< 1 ) return '';
                $key = $match[1];
                $val = isset($info[$key]) ? $info[$key]:'';
                return $val;
            }, $logTitle);

            [$url] = explode('?', $path);

            $data['title'] = $logTitle;
            $data['url'] = $url;
            $data['admin_id'] = empty($admin['id']) ? 0:$admin['id'];
            $data['ip'] = $ip;
            $data['method'] = $method;
            $data['data'] = $reqData;
            $data['code'] = $code;
            
            $data['name'] = isset($admin['nickname']) ?  $admin['nickname']: '-';

            SysLogs::create($data);
        }


        return $response;
    }
}